package main

import (
	"bytes"
	"fmt"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

type Users struct {
	Id   int64
	Name string
}

func main() {
	dsn := "root:root@tcp(127.0.0.1:3306)/test?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		fmt.Println("数据库连接失败!")
	}

	//获取按主键顺序的第一天
	user := Users{}
	db.First(&user)
	// fmt.Println(user)

	//查找所有列表
	users := []Users{}
	db.Find(&users)
	// fmt.Println(users)

	//获取一条没有指定顺序的记录
	takeUser := Users{}
	db.Take(&takeUser)
	// fmt.Println(takeUser)

	//条件查询
	findUser := Users{}
	db.Where("id = ?", 2).Find(&findUser)
	// fmt.Println(findUser)

	//创建数据
	createUser := Users{}
	createUser.Name = "创建"
	db.Create(&createUser)

	//分页查询
	page := 3
	pageSize := 2
	offset := (page - 1) * pageSize
	limitUsers := []Users{}
	db.Limit(pageSize).Offset(offset).Find(&limitUsers)
	fmt.Println(limitUsers)

	//查询总数
	var count int64
	db.Table("users").Count(&count)
	fmt.Println(count)

	//批量插入
	var buffer bytes.Buffer
	sql := "INSERT INTO `users` (`name`) values"
	if _, err := buffer.WriteString(sql); err != nil {
		fmt.Println(err)
	}
	buffer.WriteString(fmt.Sprintf("('%s'),", "cc"))
	buffer.WriteString(fmt.Sprintf("('%s')", "dd"))
	fmt.Println(buffer.String())
	db.Exec(buffer.String())
}
